/**
 * 
 */
package com.lehecai.core.service.impl.memcached;

import java.util.Calendar;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.lehecai.core.memcached.IMemcachedObject;
import com.lehecai.core.service.memcached.MemcachedService;
import com.whalin.MemCached.MemCachedClient;

/**
 * 官方推荐使用的memcached客户端
 * @author leiming
 *
 */
public class OfficialMemcachedServiceImpl implements MemcachedService {
	
	protected final Logger logger = LoggerFactory.getLogger(this.getClass().getName());
	
	private MemCachedClient memCachedClient;//ioc

	@Override
	public boolean delete(String key) throws Exception {
		return memCachedClient.delete(key);
	}

	@Override
	public IMemcachedObject get(String key) throws Exception {
		try {
			return get(key, 0);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
	}

	@Override
	public IMemcachedObject get(String key, long timeout) throws Exception {
		IMemcachedObject obj = (IMemcachedObject)memCachedClient.get(key);
		return obj;
	}
	
	@Override
	public boolean set(String key, IMemcachedObject object, int alive)
			throws Exception {
		return set(key, object, alive, 0);
	}
	
	@Override
	public boolean set(String key, IMemcachedObject object, int alive,
			long timeout) throws Exception {
		Calendar now = Calendar.getInstance();
		now.add(Calendar.SECOND, alive);
		return memCachedClient.set(key, object, now.getTime());  

	}
	
	@Override
	public Map<String, IMemcachedObject> mget(Collection<String> keys) throws Exception {
		return mget(keys, 0);
	}

	@Override
	public Map<String, IMemcachedObject> mget(Collection<String> keys,
			long timeout) throws Exception {
		if(keys == null || keys.isEmpty()){
			return null;
		}
		String[] keyArray = new String[keys.size()];
		int i = 0;
		for(String key : keys){
			keyArray[i] = key;
			i++;
		}
		Map<String, Object> mcMap = memCachedClient.getMulti(keyArray);
		Map<String, IMemcachedObject> resultMap = new HashMap<String, IMemcachedObject>();
		for(Map.Entry<String, Object> entry : mcMap.entrySet()){
			resultMap.put(entry.getKey(), (IMemcachedObject)entry.getValue());
		}
		return resultMap;
	}

	public MemCachedClient getMemCachedClient() {
		return memCachedClient;
	}

	public void setMemCachedClient(MemCachedClient memCachedClient) {
		this.memCachedClient = memCachedClient;
	}

	
	
}
